package org.whatever.aha.zjut.platform.task;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.platform.entity.competition.Competition;
import org.whatever.aha.zjut.platform.entity.competition.CompetitionStage;
import org.whatever.aha.zjut.platform.entity.competition.CompetitionStageStatus;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.service.competition.CompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageStatusService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;

import java.util.Date;
import java.util.List;


/**
 * @author Vc
 * @version 1.0
 * @Desc
 * @date 2021/10/18 22:53
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CompetitionStatusTask {
    final ProjectService projectService;
    final CompetitionStageStatusService competitionStageStatusService;
    final CompetitionService competitionService;
    final CompetitionStageService competitionStageService;

    //根据comp_stage_status 的time信息更新竞赛状态、竞赛所属项目Stu的状态
    //半小时更新一次全量数据
    @Scheduled(cron = "0 */30 * * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus() {
        log.info("开始更新竞赛状态信息");

        //获得所有未完结的比赛Id
        List<Object> compIds = competitionService.getOngoingCompId();

        //遍历所有竞赛
        for (Object compId : compIds) {
            int intCompId = (int) compId;
            //依次更新竞赛状态
            this.updateCompStatus(intCompId);
            log.info("全量竞赛状态(竞赛未开始、进行中、已结束)更新完成");

            List<CompetitionStage> stages = competitionStageService.getStageByCompId(intCompId);
            for (CompetitionStage stage : stages) {
                //依次更新竞赛阶段状态
                this.updateCompStageStatus(stage);
            }
            log.info("全量竞赛阶段（初赛复赛）状态更新完成");
        }

        log.info("竞赛状态更新完成");
    }


    public void updateCompStageStatus(CompetitionStage stage){
        List<CompetitionStageStatus> compStageStatusList = competitionStageStatusService.getCompStageStatus(stage.getStageId());
        Date date = new Date();
        //遍历status时间信息以更新
        for (CompetitionStageStatus competitionStageStatus : compStageStatusList) {
            //对阶段来说未提交前为未开始，最后一个环节（不一定是公示）后为已结束
            if (date.before(competitionStageStatus.getStatusStartTime()) && competitionStageStatus.getStatusOrder() == StatusConstant.COMPETITION_STAGE_STATUS_ORDER_SUBMIT.getCode()) {
                if(!StatusConstant.COMPETITION_STAGE_STATUS_NOT_COMMENCED.getCode().equals(stage.getStageStatus())){
                    stage.setStageStatus(StatusConstant.COMPETITION_STAGE_STATUS_NOT_COMMENCED.getCode());
                    competitionStageService.updateCompStageById(stage);
                    return;
                }
            } else if (date.after(competitionStageStatus.getStatusEndTime()) && competitionStageStatus.getStatusOrder() == compStageStatusList.size()) {
                if(!StatusConstant.COMPETITION_STAGE_STATUS_COMPLETED.getCode().equals(stage.getStageStatus())){
                    stage.setStageStatus(StatusConstant.COMPETITION_STAGE_STATUS_COMPLETED.getCode());
                    competitionStageService.updateCompStageById(stage);

                    //更新已完结比赛阶段下属项目信息
                    List<Project> projects = projectService.getProjectsByStageId(stage.getStageId());
                    for (Project project : projects) {
                        if (!StatusConstant.PROJECT_STUDENT_STATUS_COMPELETED.getCode().equals(project.getProjectStudentStatus())) {
                            project.setProjectStudentStatus(StatusConstant.PROJECT_STUDENT_STATUS_COMPELETED.getCode());
                            projectService.updateProject(project);
                        }
                    }
                    return;
                }
            } else {
                if(!StatusConstant.COMPETITION_STATUS_ONGOING.getCode().equals(stage.getStageStatus())){
                    stage.setStageStatus(StatusConstant.COMPETITION_STAGE_STATUS_ONGOING.getCode());
                    competitionStageService.updateCompStageById(stage);
                }
            }
        }
    }


    /**
     * 依次更新竞赛状态
     *
     * @param intCompId
     */
    public void updateCompStatus(int intCompId){
        List<CompetitionStage> stages = competitionStageService.getStageByCompId(intCompId);
        //遍历所有stage
        for (CompetitionStage stage : stages) {
            List<CompetitionStageStatus> compStageStatusList = competitionStageStatusService.getCompStageStatus(stage.getStageId());
            Date date = new Date();
            //遍历status时间信息以更新
            for (CompetitionStageStatus competitionStageStatus : compStageStatusList) {
                Competition competition = competitionService.getCompetitionById(intCompId);
                //初赛未提交前为未开始，复赛公示后为已结束
                if (date.before(competitionStageStatus.getStatusStartTime()) && stage.getStageOrder() == StatusConstant.COMPETITION_STAGE_PRELIMINARY.getCode() && competitionStageStatus.getStatusOrder() == StatusConstant.COMPETITION_STAGE_STATUS_ORDER_SUBMIT.getCode()) {
                    if(!StatusConstant.COMPETITION_STATUS_NOT_COMMENCED.getCode().equals(competition.getCompStatus())){
                        competition.setCompStatus(StatusConstant.COMPETITION_STATUS_NOT_COMMENCED.getCode());
                        competitionService.updateCompById(competition);
                        return;
                    }
                } else if (date.after(competitionStageStatus.getStatusEndTime()) && stage.getStageOrder() == stages.size() && competitionStageStatus.getStatusOrder() == compStageStatusList.size()) {
                    if(!StatusConstant.COMPETITION_STATUS_COMPELETED.getCode().equals(competition.getCompStatus())){
                        competition.setCompStatus(StatusConstant.COMPETITION_STATUS_COMPELETED.getCode());
                        competitionService.updateCompById(competition);
                        return;
                    }
                } else {
                    if(!StatusConstant.COMPETITION_STATUS_ONGOING.getCode().equals(competition.getCompStatus())){
                        competition.setCompStatus(StatusConstant.COMPETITION_STATUS_ONGOING.getCode());
                        competitionService.updateCompById(competition);
                    }
                }
            }
        }
    }

}
